import { Avatar, ImageUploader } from "antd-mobile";
import React, { useEffect } from "react";
import "./index.scss";
import Cloud from "leancloud-storage";
import { useUserStore } from "../../store/user";
import { userUpdate } from "../../api/user";
const getBase64 = (img: File, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
export interface IImgUploadProps {}
export default function ImgUpload(props: IImgUploadProps) {
  const [avatar, setAvatar] = React.useState<string>("");
  const { userInfo, update } = useUserStore((state) => state);
  useEffect(() => {
    if (userInfo && userInfo.avatar) {
      setAvatar(userInfo.avatar);
    }
  }, []);
  const handleUpload = async (file: File) => {
    // console.log(file);
    getBase64(file, (base64) => {
      // console.log(base64);
      let cloudFile = new Cloud.File("react-mobile-img.png", { base64 });
      cloudFile.save().then((res: any) => {
        // console.log(res);
        let avatar = res.attributes.url;
        userUpdate(userInfo!.objectId, { avatar }).then(() => {
          setAvatar(avatar);
          update({ ...userInfo!, avatar });
        });
      });
    });
    return {
      key: Math.random(),
      url: "https://file2204.h5project.cn/MV9TRAOUNhxPpzVdLN40AOsSoOm0cBk1/fx.png",
    };
  };
  return (
    <div>
      <ImageUploader upload={handleUpload}>
        <Avatar
          src={avatar}
          style={{ "--size": "64px", "--border-radius": "50%" }}
        />
      </ImageUploader>
    </div>
  );
}
